package com.alks.function.controller.finance.mtlcosts;

import com.alibaba.excel.util.StringUtils;
import com.alks.common.aop.ApiRestController;
import com.alks.common.aop.WebLogger;
import com.alks.common.utils.beanutils.ArrayUtils;
import com.alks.common.utils.excelUtils.ExcelUtils;
import com.alks.entity.data.entity.PcCostDetail;
import com.alks.entity.data.entity.PcCostTemp;
import com.alks.entity.data.response.ResponseInfo;
import com.alks.entity.exception.ServiceErrorException;
import com.alks.function.data.dto.finance.fincons.InboundDetailsDto;
import com.alks.function.data.dto.finance.ryfinance.CostDetailDto;
import com.alks.function.data.request.finance.ryfinance.*;
import com.alks.function.data.vo.finance.mtlcosts.CostDetImportVo;
import com.alks.function.service.common.BackService;
import com.alks.function.service.finance.mtlcosts.IMcBillFessService;
import com.alks.function.service.finance.ryfinance.IBillFessService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author MS
 * @since 2024/6/7上午10:04
 */
@RestController
@ApiRestController("/mtlCosts")
@Api(value = "财务部", tags = {"财务部-材料费用-费用结算作业-2","财务部-工厂-财务咨询查询"})
@Slf4j
public class McBillFessController {
    @Autowired
    private IMcBillFessService service;
    @Autowired
    private IBillFessService fessService;
    @Autowired
    private BackService backService;

    @WebLogger
    @GetMapping("/costTempQuery")
    @ApiOperation(value = "费用明细输入查询", tags = "财务部-材料费用-费用结算作业-2")
    public ResponseInfo costTempQuery() {
        return fessService.costTempQuery();
    }

    @WebLogger
    @PostMapping("/costTempAdd")
    @ApiOperation(value = "费用明细输入新增", tags = "财务部-材料费用-费用结算作业-2")
    public ResponseInfo costTempAdd(@RequestBody PcCostTemp request) {
        service.costTempAdd(request);
        return ResponseInfo.ok();
    }

    @WebLogger
    @PutMapping("/costTempUpdate")
    @ApiOperation(value = "费用明细输入数据修改", tags = "财务部-材料费用-费用结算作业-2")
    public ResponseInfo costTempUpdate(@RequestBody PcCostTemp request) {
        /*防止误输入*/
        request.setFeeStatus(null);
        request.setFeeItem(null);
        request.setFeeSlipNo(null);
        fessService.costTempUpdate(request);
        return ResponseInfo.ok();
    }

    @WebLogger
    @PutMapping("/costTempDelete")
    @ApiOperation(value = "费用明细输入数据删除", tags = "财务部-材料费用-费用结算作业-2")
    public ResponseInfo costTempDelete(@RequestParam @ApiParam("序号") Integer item) {
        return service.costTempDelete(item);
    }

    @WebLogger
    @PostMapping("/costDetailQuery")
    @ApiOperation(value = "费用查询明细查询", tags = "财务部-材料费用-费用结算作业-2")
    public ResponseInfo costDetailQuery(@RequestBody CostDetailQueryRequest request) {
        return ResponseInfo.ok(service.costDetailQuery(request));
    }

    @WebLogger
    @PostMapping("/costTempToDetail")
    @ApiOperation(value = "费用明细增加", tags = "财务部-材料费用-费用结算作业-2")
    public ResponseInfo costTempToDetail(@RequestBody CostTempToDetailRequest request) {
        return service.costTempToDetail(request);
    }

    @WebLogger
    @PostMapping("/costDetailToTemp")
    @ApiOperation(value = "费用明细修改/扣款", tags = "财务部-材料费用-费用结算作业-2")
    public ResponseInfo costDetailToTemp(@RequestBody List<CostDTTRequest> request,
                                         @RequestParam @ApiParam(allowEmptyValue = true, value = "1.修改 2.指定扣款") Integer type) {
        return service.costDetailToTemp(request, type);
    }

    @WebLogger
    @PutMapping("/costDetailUp")
    @ApiOperation(value = "费用明细更新(包括结算)", tags = "财务部-材料费用-费用结算作业-2")
    public ResponseInfo costDetailUpdate(@RequestBody List<CostDetUpRequest> request,
                                         @RequestParam(required = false) @ApiParam(value = "1.结算 2.取消结算", required = true) Integer financeType,
                                         @RequestParam(required = false) @ApiParam("结算月份") String financeYymm) {
        return service.costDetailUpdate(request, financeType, financeYymm);
    }

    @WebLogger
    @PostMapping("/costDetailDelete")
    @ApiOperation(value = "费用明细删除", tags = "财务部-材料费用-费用结算作业-2")
    public ResponseInfo costDetailDelete(@RequestBody @ApiParam(required = true,value = "序号") List<Integer> idList) {
        return service.costDetailDelete(idList);
    }

    @WebLogger
    @PutMapping("/costDetail/import")
    @ApiOperation(value = "导入", tags = "财务部-材料费用-费用结算作业-2")
    public ResponseInfo costDetailImport(MultipartFile file) {
        List<PcCostDetail> read = ExcelUtils.passRow(2).read(file, PcCostDetail.class);
        /*数据校验*/
        for (PcCostDetail detail : read) {
            /*允许指令为空*/
            if (StringUtils.isNotBlank(detail.getLotNo())) {
                backService.getRyLotCheck(detail.getLotNo());
            }
            String vendorNo = backService.getVendorNoByName(detail.getVendorName());
            detail.setVendorNo(vendorNo);
        }
        /*写入数据*/
        service.costInsert(read);
        return ResponseInfo.ok();
    }

    @WebLogger
    @PostMapping("/costDetail/export")
    @ApiOperation(value = "导出", tags = "财务部-材料费用-费用结算作业-2")
    public void costDetailExport(@RequestBody CostDetailQueryRequest request, HttpServletResponse response) {
        request.setPageSize(-1);
        String templet = "费用结算作业_2模版.xls";
        String fileName = "费用结算作业" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyMMdd")) + ".xls";
        Map<String, Object> map = service.costDetailQuery(request);
        List<CostDetailDto> dtoList = (List<CostDetailDto>) map.get("dtos");
        if (ArrayUtils.isEmpyt(dtoList)){
            throw new ServiceErrorException("暂无数据可导出");
        }
        CostDetailDto dto = new CostDetailDto();
        /*补充合计*/
        dto.setCostUnit("合计");
        BigDecimal amtSum = dtoList.stream()
                .map(CostDetailDto::getAmt)
                .filter(Objects::nonNull)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        dto.setAmt(amtSum);
        dtoList.add(dto);
        /*生成EXCEL*/
        try {
            ExcelUtils.creatByTemplate(response, templet, fileName, dtoList);
        } catch (Exception e) {
            throw new ServiceErrorException("导出失败");
        }
    }
}